<template>
  <div class="basic-box">
    <div class="header">
      <div class="left">
        <el-image class="cover" :src="memberDetail.avatar" style="height: 300px" />
        <div style="display: flex;flex-direction: column;width:100%;flex-wrap: wrap">
          <div v-for="(item,index) in memberMapFilter" :key="index" class="cell">
            <div class="title">
              {{ item.title }} :&nbsp;
            </div>
            <div v-if="item.key !== 'position' && item.key !== 'org' || memberDetail[item.key].length > 0" class="content">
              {{ memberDetail[item.key] }}
            </div>
          </div>
        </div>
      </div>
      <div class="right">
        <el-button icon="el-icon-edit" type="primary" @click="handleUpdate()">编辑</el-button>
        <el-button v-if="$store.getters.isAdmin" icon="el-icon-edit" type="danger" plain @click="resetPassword">重置密码</el-button>
      </div>
    </div>
    <div class="summary">
      <div class="summary-title">
        成员简介 :
      </div>
      <div class="summary-content">
        {{ memberDetail.intro }}
      </div>
    </div>
    <el-dialog title="编辑成员信息" :visible.sync="editDialogFormVisible">
      <el-form ref="dataForm" label-position="left" label-width="70px" style="width: 80%; margin-left:50px;">
        <el-form-item label="姓名" prop="username">
          <el-input v-model="dialogTemp.username" />
        </el-form-item>
        <el-form-item label="班级" prop="password">
          <el-input v-model="dialogTemp.uclass" />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="dialogTemp.gender" class="filter-item" placeholder="Please select">
            <el-option v-for="item in genderOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="dialogTemp.status" class="filter-item" placeholder="Please select">
            <el-option v-for="item in statusOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="$store.getters.isAdmin">
          <template slot="label" style="display: flex;flex-direction: row;align-items: center">
            职位 <span style="align-self: flex-start" class="el-icon-circle-plus-outline text-primary" @click="handleAddPosition" />
          </template>
          <span v-if="dialogTemp.positionList != null && dialogTemp.positionList.length <=0" class="text-info">点击左侧+号添加职位</span>
          <el-tag v-for="(item,index) in dialogTemp.positionList" :key="index" style="margin-right: 10px" closable type="success" @close="deletePosition(index)">{{ item.name }}</el-tag>
        </el-form-item>
        <el-form-item label="简介">
          <el-input v-model="dialogTemp.intro" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="Please input" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog title="重置密码确认" :visible.sync="resetDialogFormVisible" style="width: 50%;margin: 0 auto">
      <div ref="dataForm" style="width: 100%;" class="text-danger">
        <span><i class="el-icon-warning-outline" />请在重置密码前告知账号有关人员重置后密码</span>
        <div class="content">
          <br>
          <el-input v-model="newPassword" placeholder="请输入重置后密码" />
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetDialogFormVisible = false">
          取消
        </el-button>
        <el-button type="danger" @click="handleReset">
          确定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog title="添加职位" :visible.sync="positionDialogFormVisible">
      <el-form ref="dataForm" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-cascader v-model="positionTemp" :options="positionOptions" />
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="positionDialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="addPosition">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchMemberDetail, updateMember } from '@/api/member'
import { resetPassword } from '@/api/user'
import { getPositionId, getPositionOptions } from '@/api/role'
import { Message } from 'element-ui'

export default {
  username: 'MemberDetail',
  data() {
    return {
      genderOptions: ['男', '女'],
      statusOptions: ['活跃', '离队', '退役'],
      positionOptions: null,
      isEditMode: false,
      resetDialogFormVisible: false,
      editDialogFormVisible: false,
      positionDialogFormVisible: false,
      newPassword: '',
      username: '肥宅俱乐部',
      memberDetail: {
        id: '@increment',
        gender: '@Gender_ch',
        username: '@first',
        password: '@string',
        uclass: '@Major' + '@string(number,3)',
        org: '@Org',
        position: '@Position',
        status: 'Status',
        img: ''
      },
      dialogTemp: {
        importance: 1,
        intro: '',
        title: '',
        type: '',
        status: '',
        password: '',
        positionList: []
      },
      positionTemp: {},
      categoryList: [
        { value: '0', label: '禁用' },
        { value: '1', label: '启用' }
      ],
      memberMap: [
        { key: 'id', title: '学号' },
        { key: 'username', title: '姓名' },
        { key: 'gender', title: '性别' },
        // { key: 'password', title: '密码' },
        { key: 'uclass', title: '班级' },
        { key: 'org', title: '社团' },
        { key: 'position', title: '职位' },
        { key: 'status', title: '状态' },
        { key: 'intro', title: '简介' }
      ]
    }
  },
  computed: {
    memberMapFilter() {
      return this.memberMap.filter(
        item => {
          return item.key !== 'intro'
        }
      )
    }
  },
  created() {
    this.fetchInfo()
    getPositionOptions().then(res => { this.positionOptions = res.data.items })
  },
  methods: {
    setTagsViewTitle() {
      console.log(this.username)
      this.$route.meta.title = this.username
      const currentView = this.$store.getters.visitedViews[this.$store.getters.visitedViews.findIndex(
        (item) => item.path === this.$route.path
      )]
      if (currentView != null) {
        currentView.title = this.username
      }
      // this.$store.getters.breadcrumb.getBreadcrumb()
      // const route = Object.assign({}, this.tempRoute, { title: `${this.username}`})
      // this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    setPageTitle() {
      document.title = `${this.username}`
    },
    fetchInfo() {
      const id = this.$route.params && this.$route.params.id
      console.log(id)
      fetchMemberDetail(id).then(
        res => {
          var detail = res.data.items
          detail['org'] = []
          detail['position'] = []
          for (const i in detail.roles) {
            detail.org += detail.roles[i].org.name + ', '
            detail['position'] += detail.roles[i].org.name + detail.roles[i].position + ', '
          }
          if (detail.roles.length > 0) {
            detail['org'] = detail['org'].substring(0, detail.org.lastIndexOf(','))
            detail['position'] = detail.position.substring(0, detail.position.lastIndexOf(','))
          }
          this.username = res.data.items.username
          this.setPageTitle()
          this.setTagsViewTitle()
          console.log(detail)
          this.memberDetail = detail
        }
      )
    },
    handleAddPosition() {
      this.positionDialogFormVisible = true
    },
    addPosition() {
      console.log(this.positionTemp)
      getPositionId(this.positionTemp[1]).then(
        res => {
          var i = 0
          for (; i < this.dialogTemp.positionList.length; i++) {
            if (this.dialogTemp.positionList[i].id === res.data.items.id) {
              break
            }
          }
          if (i >= this.dialogTemp.positionList.length) {
            this.dialogTemp.positionList.push(res.data.items)
          } else {
            Message({
              message: '不能重复添加职位',
              type: 'error',
              duration: 1000
            })
          }
          this.positionDialogFormVisible = false
          // this.positionTemp = []
        }
      )
    },
    deletePosition(index) {
      const list = { positionList: this.dialogTemp.positionList }
      console.log(list)
      list.positionList.splice(index)
      this.dialogTemp = Object.assign(list, this.dialogTemp)
    },
    handleUpdate() {
      this.dialogTemp = Object.assign({}, this.memberDetail) // copy obj
      this.dialogTemp['positionList'] = []
      for (const i in this.memberDetail.roles) {
        this.dialogTemp.positionList.push({
          name: this.memberDetail.roles[i].org.name + this.memberDetail.roles[i].position,
          id: this.memberDetail.roles[i].id
        })
      }
      this.dialogStatus = 'update'
      this.editDialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      const tempData = Object.assign({}, this.dialogTemp)
      tempData.timestamp = +new Date(tempData.timestamp)
      updateMember(tempData).then(() => {
        this.editDialogFormVisible = false
        this.fetchInfo()
        this.$notify({
          title: 'Success',
          message: 'Update Successfully',
          type: 'success',
          duration: 2000
        })
      })
    },
    resetPassword() {
      this.resetDialogFormVisible = true
    },
    handleReset() {
      this.resetDialogFormVisible = false
      resetPassword({ id: this.memberDetail.id, password: this.newPassword })
    },
    destroyDialog() {
      this.editData = {}
      this.isEditMode = false
    }
  }
}
</script>

<style scoped lang="scss">
  .basic-box{
    margin-top: 40px;
    padding: 30px 5%;
    border-radius: 10px;
    width: 100%;
  }
  .header{
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    .left{
      width: 80%;
      display: flex;
      flex-direction: row;
      align-items: flex-start;
      justify-content: flex-start;
      .cover{
        border-radius: 10px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)
      }
    }
    .right{
      /*width: 20%;*/
      display: flex;
      flex-direction: row;
      align-items: flex-start;
      /*margin-right: 20px;*/
      /*justify-content: flex-end;*/
    }
  }
  .cell{
    display: flex;
    flex-direction: row;
    align-items: center;
    margin:10px;
    .title{
      font-size: 20px;
      font-weight:800;
      color: #11A983;
    }
    .title-edit{
      font-size: 20px;
      font-weight:800;
      color: #11A983;
      width: 150px;
    }
    .content{
      font-size: 20px;
      font-weight: 500;
      width: 300px;
    }
  }
  .summary{
    margin: 30px 40px;
    width: 90%;
    .summary-title{
      font-size: 25px;
      color: #2c3e50;
      font-weight: bolder;
    }
    .summary-content{
      margin-top: 20px;
      font-size: 20px;
    }
  }
  .el-icon-circle-plus-outline:hover{
    color: #5ec78f;
  }
  .el-icon-circle-plus-outline:active{
    color: #1a9b70;
  }
</style>
